﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Common.Net.Utilities;

namespace Common.Net.DesignByContract
{
    public static class RequireArg
    {
        static string Format<T>(Expression<Func<T>> func)
        {
            return ExpressionFormatter.Format(func);
        }

        [Obsolete("Prefer method with lambda instead")]
        public static void NotNull<T>(T arg, string argName)
        {
            if (arg == null)
                throw new ArgumentNullException(argName);
        }

        public static T NotNull<T>(Expression<Func<T>> arg)
        {
            T value = arg.Compile()();

            if (value == null)
                throw new ArgumentNullException(Format(arg));

            return value;
        }

        public static void Complies(Expression<Func<bool>> condition)
        {
            Complies(condition.Compile()(), "Condition {0} was not met", Format(condition));
        }

        public static void Complies(Expression<Func<bool>> condition, string format, params object[] args)
        {
            Complies(condition.Compile()(), format, args);
        }

        public static void Complies(bool condition, string format, params object[] args)
        {
            if (!condition)
                throw ExceptionFactory.Argument(format, args);
        }
    }
}
